import React from "react";
import {Dimensions, Image, Text, View} from "react-native";
import Constants from "expo-constants";
import * as Updates from "expo-updates";
import {UpdateEventType} from "expo-updates";

const {width: DEVICE_WIDTH} = Dimensions.get("window");

const SplashImage = ({ onUpdate }: { onUpdate: Function }): React.ReactElement => {

    const [updateText, setUpdateText] = React.useState('检查更新...');

    // 在呈现应用程序之前加载我们需要的任何资源或数据
    React.useEffect(() => {
        const checkUpdate = async ()=> {
            let slug = Constants.manifest.slug;//应用名称
            console.log("应用名称：" + slug);
            if (slug !== 'my-app2') {
                console.log("=============================进入更新代码=============================");
                try {
                    const update = await Updates.checkForUpdateAsync();
                    if (update.isAvailable) {
                        setUpdateText('有新的更新包正在检查...');
                        await Updates.fetchUpdateAsync();
                    }
                } catch (e) {
                    setUpdateText('更新异常！请重启应用...');
                    console.log("=============================更新失败=============================");
                    console.log(e);
                }
                console.log("=============================退出更新代码=============================");
                Updates.addListener((event)=> {
                    console.log("=============================进入更新监听=============================");
                    switch (event.type) {
                        case UpdateEventType.UPDATE_AVAILABLE:
                            setUpdateText('新的更新已完成下载...');
                            console.log('新的更新已完成下载，现在存储在设备的缓存中。');
                            Updates.reloadAsync();
                            break;
                        case UpdateEventType.NO_UPDATE_AVAILABLE:
                            console.log('没有可用的更新，最新捆绑包已经在运行。');
                            break;
                        case UpdateEventType.ERROR:
                            setUpdateText('尝试获取最新更新时发生错误！请重启应用...');
                            console.log('尝试获取最新更新时发生错误。');
                    }
                    //更新完毕
                    onUpdate(true)
                });
            }else{
                onUpdate(true)
            }
        }
        checkUpdate().then(() => {});
    }, []);

    return (
        <View style={{flex: 1}}>
            <Image
                style={{
                    flex: 1, resizeMode: 'stretch', width: undefined, height: undefined
                }}
                source={require('./../assets/images/splash.png')}
                fadeDuration={0}/>
            <Text style={{
                position: "absolute",
                bottom: 0,
                width: DEVICE_WIDTH,
                textAlign: 'center',
                color: '#3b3b3b'
            }}>{updateText}</Text>
        </View>
    )

};

export default SplashImage